package com.链表2;

public  class ListNode3 {
    int val;
    ListNode3 next;
    ListNode3(int x){
        this.val = x;
    }
}
class MyLinkedList3 {
    //哨兵节点
    ListNode3 head ;
    int size ;
    public  MyLinkedList3(){
        this.head = new ListNode3(0);
        this.size = 0;
    }
    /** Get the value of the index-th node in the linked list. If the index is invalid, return -1. */
    public int get(int index) {
        ListNode3 node = head;
        for(int i = 0;i<index+1;i++){
            node = node.next;
        }
        return node.val;
    }

    /** Add a node of value val before the first element of the linked list. After the insertion, the new node will be the first node of the linked list. */
    public void addAtHead(int val) {
        addAtIndex(0,val);
    }

    /** Append a node of value val to the last element of the linked list. */
    public void addAtTail(int val) {
        addAtIndex(size,val);

    }

    /** Add a node of value val before the index-th node in the linked list. If index equals to the length of linked list, the node will be appended to the end of linked list. If index is greater than the length, the node will not be inserted. */
    public void addAtIndex(int index, int val) {
        if(index > size ){
            return;
        }
        if(index < 0){
            index  = 0;
        }
        size++;
        ListNode3 node = head;
        //此处要满足三个需求，1，添加头部，2.添加尾部，
        // 3，添加中间：如果 index 等于链表的长度，则该节点将附加到链表的末尾。
        // 如果 index 大于链表长度，则不会插入节点。
        // 如果index小于0，则在头部插入节点。
        for(int i  = 0 ;i<index;i++){
            node = node.next;
        }
        ListNode3 add = new ListNode3(val);
        add.next = node.next;
        node.next = add;
    }

    /** Delete the index-th node in the linked list, if the index is valid. */
    public void deleteAtIndex(int index) {
        ListNode3 node = head;
        if(index >= size || index < 0){
            return;
        }
        size--;
        for(int i = 0;i<index;i++){
            node = node.next;
        }
        node.next = node.next.next;


    }
    public String toString(){
        StringBuilder builder = new StringBuilder();
        ListNode3 node = head;
        builder.append(String.format("容量:%s，链表{",size));
        while (node != null){
            builder.append(String.format("[value:%s]",head.val));
            node = node.next;
        }
        builder.append("}");
        return builder.toString();
    }
    public static void main(String[] args) {
        MyLinkedList3 link = new MyLinkedList3();
        System.out.println(link.toString());

        link.addAtHead(3);
//        link.addAtHead(2);
//        link.addAtHead(1);
//        link.addAtTail(6);
//        link.addAtIndex(3,4);
        //link.addAtHead(0);

        System.out.println(link.toString());
    }
}